package com.wzy.mall.service.client.impl;

import com.wzy.mall.mapper.clientMapper.OrderMapper;
import com.wzy.mall.model.bo.clientBO.OrderAddBO;
import com.wzy.mall.model.bo.clientBO.OrderCartSettleBO;
import com.wzy.mall.model.bo.clientBO.OrderCartSettleListBO;
import com.wzy.mall.model.bo.clientBO.OrderSendCommentBO;
import com.wzy.mall.model.pojo.clientPOJO.CommentPOJO;
import com.wzy.mall.model.pojo.clientPOJO.OrderPOJO;
import com.wzy.mall.model.pojo.clientPOJO.SpecIdAndNumPOJO;
import com.wzy.mall.model.vo.clientVO.OrderCartShowVO;
import com.wzy.mall.service.client.OrderService;
import com.wzy.mall.utils.HTTPUtils;
import com.wzy.mall.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class OrderServiceImpl implements OrderService {

    public int addOrder(OrderAddBO orderAddBO) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);

        int result = 0;
        try {

            // 当提交订单的状态为1（已付款）时，减少库存
            if (orderAddBO.getState() == 1) {
                // 减少库存
                result = decreaseStocknum(orderAddBO.getGoodsDetailId(), orderAddBO.getNum(), mapper);
                if(result != 200) {
                    // 库存量出现问题
                    return result;
                }
            }

            // 根据用户昵称获取用户id、收件人、地址、电话
            // 根据规格ID获取商品ID、商品名、规格名、单价
            // 封装进POJO对象
            OrderPOJO orderPOJO = mapper.selectUserAndGoods(orderAddBO);
            //System.out.println(orderPOJO);

            // 将前端传来的数据封装进POJO对象中
            orderPOJO.setSpecId(orderAddBO.getGoodsDetailId());
            orderPOJO.setGoodsNum(orderAddBO.getNum());
            orderPOJO.setStateId(orderAddBO.getState());
            orderPOJO.setAmount(orderAddBO.getAmount());
            orderPOJO.setNickname(orderAddBO.getToken());
            // false表示未评价
            orderPOJO.setHasComment(false);

            // 向订单表中插入数据
            result = mapper.insertOrder(orderPOJO);

            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

        return result;
    }

    private int decreaseStocknum(int goodsDetailId, int num, OrderMapper mapper) {

        // 根据规格ID获取商品存货量
        int stockNum = mapper.selectGoodsStockBySpecID(goodsDetailId);
        // 判断购买数量是否大于存货量
        stockNum = stockNum - num;
        if(stockNum < 0) {
            // 库存量不足，回报601
            return 601;
        } else {
            int result = 0;
            // 更新stockNum
            result = mapper.updateSpecStocknum(goodsDetailId, stockNum);

            if(result != 0) {
                // 库存量修改成功，回报200
                return 200;
            } else {
                // 库存量修改失败，回报505
                return 505;
            }
        }
    }

    public List<OrderCartShowVO> getOrderByState(String state, String token) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);

        List<OrderCartShowVO> orderCartShowVOList = null;
        try {
            orderCartShowVOList = mapper.getOrderByState(state, token);
            if(orderCartShowVOList != null) {
                // 拼接图片路径前缀
                String imageBaseURL = HTTPUtils.getImageBaseURL();
                for (OrderCartShowVO orderCartShowVO : orderCartShowVOList) {
                    orderCartShowVO.getGoods().setImg(imageBaseURL + orderCartShowVO.getGoods().getImg());
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

        return orderCartShowVOList;
    }

    public int settleAccounts(OrderCartSettleListBO orderCartSettleListBO) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);



        // 先处理BO对象
        List<OrderCartSettleBO> cartList = orderCartSettleListBO.getCartList();
        // 遍历里面的订单数据，分别更新
        int result = 0;
        try {
            for (OrderCartSettleBO orderCartSettleBO : cartList) {

                Integer orderId = orderCartSettleBO.getId();
                Integer goodsNum = orderCartSettleBO.getGoodsNum();

                // 根据订单ID获取规格ID
                int goodsDetailId = mapper.selectSpecIDByOrderID(orderId);

                // 减少库存
                result = decreaseStocknum(goodsDetailId, goodsNum, mapper);
                if(result != 200) {
                    // 库存量出现问题
                    return result;
                }

                result = mapper.updateOrder(orderCartSettleBO);
                if(result == 0) {
                    throw new RuntimeException("Update Filed");
                }
            }
            sqlSession.commit();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return result;
    }

    public int updateOrderState(int id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);

        int result = 0;
        try {
            // 根据OrderId获取规格ID和商品数量
            SpecIdAndNumPOJO specIdAndNumPOJO = mapper.selectSpecIdAndNumByOrderID(id);

            // 减少库存
            result = decreaseStocknum(specIdAndNumPOJO.getSpecId(), specIdAndNumPOJO.getGoodsNum(), mapper);
            if(result != 200) {
                // 库存量出现问题
                return result;
            }

            result = mapper.updateOrderState(id, 1);

            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

        return result;
    }

    public int deleteOrder(int id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);

        int result = 0;
        try {
            result = mapper.changeVisible(id);

            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

        return result;
    }

    public int confirmReceive(int id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);

        int result = 0;
        try {
            result = mapper.updateOrderState(id, 3);

            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

        return result;
    }

    public int insertComment(OrderSendCommentBO orderSendCommentBO) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);

        // 根据订单号查找用户id、昵称、商品id、商品名、规格id、规格名
        // POJO
        CommentPOJO commentPOJO = mapper.selectCommentInfo(orderSendCommentBO.getOrderId());

        commentPOJO.setCommentMsg(orderSendCommentBO.getContent());
        commentPOJO.setScore(orderSendCommentBO.getScore());

        int result = 0;
        try {
            result = mapper.insertComment(commentPOJO);
            if(result != 0) {
                mapper.updateOrderCommentState(commentPOJO.getOrderId());
            }

            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

        return result;
    }

}
